package com.swdegao.iot.netty.server.channelhandler;

import com.swdegao.iot.SwdegaoIotMgtServerApplication;
import com.swdegao.iot.netty.entity.HandlerMessage;
import com.swdegao.iot.netty.entity.Parameter;
import com.swdegao.iot.netty.utils.ConvertUtils;
import com.swdegao.iot.netty.utils.RedisUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @Author:zt
 * @Date: Created in 8:20 2018\3\2 0002
 */
public class OutSendMessgaeHandler extends SimpleChannelInboundHandler<HandlerMessage> {

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	private final static Logger logger = LoggerFactory.getLogger(OutSendMessgaeHandler.class);
    @Autowired
    private RedisUtils redisUtils = SwdegaoIotMgtServerApplication.getBean(RedisUtils.class);

    @SuppressWarnings("unused")
	private String tempTime = null;//用于比较心跳是否超时
    private Boolean flag = true;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HandlerMessage msg) throws Exception {

		Byte type = msg.getActionTpye();
		//数据类型判断
        switch (type){
            case (byte) 0x81:
            	//注册包
            	msg.setSendMsg(GetSuccessSignal(msg.getImei(), type, true));
            	ChannelFuture cf = ctx.writeAndFlush(msg.getSendMsg());
            	cf.addListener(new ChannelFutureListener() {
					@Override
					public void operationComplete(ChannelFuture arg0) throws Exception {
						// 检查操作的状态
		                if (!cf.isSuccess()) {
		                	if(flag) {
		                		ctx.writeAndFlush(msg.getSendMsg());
		                		flag = false;
		                	}

		                }
					}
				});
                break;
            case (byte) 0x82:
            	//心跳包
            	msg.setSendMsg(GetSuccessSignal(msg.getImei(), type, true));
            	ctx.writeAndFlush(msg.getSendMsg());
                break;
            case (byte) 0x83:
            	//数据包
                break;
            case (byte) 0x84:
            	//时间同步包
            	msg.setSendMsg(ToDeviceClockMsg(msg.getImei(), type));
            	ctx.writeAndFlush(msg.getSendMsg());
            	//存储问题答案
				//redisUtils.lPush(msg.getImei()+Parameter.imei_info_downdata,JSON.toJSONString(msg.getSendMsg()));//存储所有updata数据
                break;
            case (byte) 0x85:
            	//正对与主动上报的数据回复
            	msg.setSendMsg(ToDeviceClockMsg(msg.getImei(), type));
            	ctx.writeAndFlush(msg.getSendMsg());
            	//redisUtils.lPush(msg.getImei()+Parameter.imei_info_downdata,JSON.toJSONString(msg.getSendMsg()));//存储所有updata数据
                break;
        }

        ctx.fireChannelRead(msg);
	}

	public String getTimeNow() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(new Date());
	}

	/**
	 * 获取超时时间
	 * @param timeNow
	 */
	public String getTimeOut(String timeNow) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar cal = new GregorianCalendar();

		try {
			cal.setTime(df.parse(timeNow));
			cal.add(Calendar.SECOND, Parameter.outtime_hear);

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return df.format(cal.getTime());
	}

	/**
	 * 比较超时时间，是否超时
	 */
	public int CompareOutTime(String timeNow,String timeAfter, SimpleDateFormat timestampFormat)
	{
        if(timeNow.equals(timeAfter)) // same
            return 1;
        try {
            Date timesN = timestampFormat.parse(timeNow);
            Date timesA = timestampFormat.parse(timeAfter);
            if(timesA.after(timesN)) // time 1 is newer
                return 1;
            else return -1;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 1;
	}

	/**
	 *
	 * @param imei
	 * @param type
	 * @return
	 */
	public ByteBuf ToDeviceClockMsg(String imei,byte type)
     {
		 SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		 String date = df.format(new Date());
		 byte[] temp2_ = ConvertUtils.getDateFromStr(date, 6);
         byte[] msg = new byte[22 + temp2_.length];
         msg[0] = (byte) 0x80;
         msg[1] = 0x28;
         msg[2] = 0;
         msg[3] = type;

         byte[] temp = imei.getBytes();
         System.arraycopy(temp, 0, msg, 4, 15);//类型、imei

         //byte[] temp = ConvertUtils.getByte(Integer.parseInt(imei), 15);
		 //System.arraycopy(temp, 0, msg, 4, 15);
         System.arraycopy(temp2_, 0, msg, 19, 6);
         msg[msg.length - 3] = ConvertUtils.getTotalForByte(msg);
         msg[msg.length - 2] = 0x0d;
         msg[msg.length - 1] = 0x0a;
         return Unpooled.wrappedBuffer(msg);
     }


	public ByteBuf GetSuccessSignal(String imei,byte type,boolean suc) {
		byte[] msg = new byte[23];
        msg[0] = (byte) 0x80;
        msg[1] = 0x23;
        msg[2] = 0;
        msg[3] = type;
        byte[] temp = imei.getBytes();
        System.arraycopy(temp, 0, msg, 4, 15);//类型、imei
        msg[19] = (byte)(suc ? 0x73 : 0x74);//应答状态
        msg[20] = ConvertUtils.getTotalForByte(msg);//校验和
        msg[21] = 0x0d;
        msg[22] = 0x0a;
		return  Unpooled.wrappedBuffer(msg);
	}
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
	    	Channel incoming = ctx.channel();
			System.out.println("client "+incoming.remoteAddress()+"异常"+cause.getMessage());
	        // 当出现异常就关闭连接
	        cause.printStackTrace();
	    }
}
